import { useEffect, useRef, useState } from 'react';
import styles from './index.module.less';
import { CaretDownOutlined, DownOutlined, UpOutlined } from '@ant-design/icons';
import { Button, InputNumber, message, Tooltip } from 'antd';
import { useAtomValue, useSetAtom } from 'jotai';
import { panKouPriceAtom, reloadOrderAtom } from '@/stores';
import {
  contractUnits,
  getUserInfoByApi,
  handleOrderTypePrice,
  handleOrderZhiYing,
  lunXunTime,
} from '@/utils/helper';
import UnitModal from './UnitModal';
import { contractAccount, contractApi, keYongMoneyApi, positionsApi, submitOrderApi } from '@/api';
import LeverModal from './LeverModal';
import { checkKeYongMoney, isLocal, isSuccess, orderText } from '@/utils';
import TradeStrategy from './TradeStrategy';
import useRoute from '@/hooks/useRoute';
import MyButton from '../components/MyButton';
import BaoZhengJin from './BaoZhengJin';
import useUserInfo from '@/hooks/useUserInfo';
import { useInterval } from 'ahooks';
import PubSub from 'pubsub-js';
import store from 'storejs';

const tablist = [
  { key: 'xianJia', title: '限价' },
  { key: 'shiJia', title: '市价' },
];

export default function SubmitOrder() {
  const panKouPrice = useAtomValue(panKouPriceAtom);
  const zhiYingRef = useRef<any>(null);
  const [curTab, setCurTab] = useState<any>('xianJia'); // 当前tab 限价、市价
  const [positionType, setPositionType] = useState<'all' | 'zhu'>(); // 仓位类型 all全仓,zhu逐仓
  const [lever, setLever] = useState<any>();
  const [price, setPrice] = useState<any>(0);
  const [num, setNum] = useState<any>();
  const [coinData, setCoinData] = useState<any>({});
  const [units] = useState<any>(contractUnits);
  const [unit, setUnit] = useState<any>(contractUnits[1]);
  const [account, setAccount] = useState<any>({});
  const [open, setOpen] = useState(false);
  const [openLever, setOpenLever] = useState(false);
  const setReloadOrder = useSetAtom(reloadOrderAtom);
  const { getPageParams } = useRoute();
  const curContract = getPageParams('contract');
  const [buyLoading, setBuyLoading] = useState(false);
  const [sellLoading, setSellLoading] = useState(false);
  const [minNum, setMinNum] = useState<any>();
  const [userInfo, setUserInfo] = useState<any>({});
  const [keYongMoney, setKeYongMoney] = useState<any>(0);
  const [keYongMoneyNew, setKeYongMoneyNew] = useState<any>(0);

  useEffect(() => {
    getCurrentCoin();
    getContractAccount(); // 合约账号
    setTimeout(() => {
      getUserInfo();
      getKeYongMoney();
    }, 100);
    // 加仓减仓时，重新获取可用余额
    const mySub = PubSub.subscribe('updataKeYongYuE', (key: any, data: any) => {
      console.log('发布订阅-key: ', key);
      if (key === 'updataKeYongYuE') {
        setTimeout(() => {
          console.log('====8888');
          getKeYongMoney();
          getKeYongMoneyNew();
        }, 500);
      }
    });
    return () => {
      // 取消订阅
      PubSub.unsubscribe(mySub);
    };
  }, []);

  // 轮询
  useInterval(() => {
    // getKeYongMoney();
    getKeYongMoneyNew();
  }, lunXunTime);

  useEffect(() => {
    setMinNum(+Number(price * coinData?.quanto_multiplier).toFixed(1));
  }, [price]);

  // 合约详情
  async function getCurrentCoin() {
    const val: any = await contractApi({ contract: curContract });
    const res: any = val?.data;
    setCoinData(res);
    setPrice(res?.last_price);
    getPositionsApi(res); // 获取杠杆信息-仓位列表
  }

  // 下单,isSell是否卖出
  async function buy(sell = false) {
    // 检测余额够不够
    if (!checkKeYongMoney(keYongMoneyNew)) return false;
    let isSell = sell;
    let params: any = {
      contract: coinData?.name,
      text: orderText,
      reduce_only: false,
      iceberg: 0,
      stp_act: '-',
    };
    // * 下单时处理限价、市价的参数
    const orderTypePriceRes = handleOrderTypePrice(curTab, price);
    params = { ...params, ...orderTypePriceRes };
    // * 处理并检测下单数量
    if (!handleNum()) return false;
    params.size = (isSell ? -1 : 1) * handleNum();
    // * 处理员工下单方向问题
    if (!isSell) setBuyLoading(true);
    if (isSell) setSellLoading(true);
    params.size = userInfo?.direction * params.size;
    console.log('params: 下单', params);
    // api: 下单
    const res: any = await submitOrderApi(params);
    setBuyLoading(false);
    setSellLoading(false);
    console.log('res: 下单结果 ', res);
    if (isSuccess(res)) {
      setReloadOrder(true);
      message.success('成功');
      // 刷新余额
      getKeYongMoney();
      getKeYongMoneyNew();
    }
  }

  // 处理并检测下单数量
  function handleNum() {
    if (!num) {
      message.error('下单数量不能为空');
      return false;
    }
    let size = num;
    // 校验
    if (size < minNum) {
      message.error('下单数量不能小于最小下单量');
      return false;
    }
    if (unit?.value === 'USDT') size = Math.floor(num / (price * coinData?.quanto_multiplier)); // 转化为张
    return size;
  }

  // 获取员工信息
  // const getUserInfo = async () => setUserInfo(await getUserInfoByApi());
  const { getUserInfo: getUserInfo2 } = useUserInfo();
  async function getUserInfo() {
    const res = await getUserInfo2();
    // console.log('getUserInfo2:getUserInfo2 ', res);
    // getKeYongMoney();
    getKeYongMoneyNew();
    setUserInfo(res);
  }

  // 修改价格
  function changePrice(num: number) {
    setPrice(Number((Number(price) + num).toFixed(1)));
  }

  // 合约账号BaoZhengJin
  async function getContractAccount() {
    const res: any = await contractAccount();
    // console.log('res: 合约账号: ', res);
    setAccount(res?.data);
  }

  // 获取杠杆信息-仓位列表
  async function getPositionsApi(coinData: any) {
    const res: any = await positionsApi();
    // console.log('res: ', res);
    res.data = 0;
    const arr = res?.data ? res?.data?.filter((item: any) => item.contract === curContract) : [];
    // 如果没有杠杆信息怎设置为全仓10x（默认10x）
    if (arr.length === 0) {
      setPositionType('all');
      setLever(Number(coinData?.cross_leverage_default));
      return;
    }
    const data = arr[0];
    setPositionType(data?.leverInfo?.type);
    setLever(data?.leverInfo?.lever);
  }

  // 点击盘口设置价格
  useEffect(() => {
    if (panKouPrice > 0) setPrice(panKouPrice);
  }, [panKouPrice]);

  // 获取可用资产
  async function getKeYongMoney() {
    const res: any = (await keYongMoneyApi())?.data;
    // console.log('res: 获取可用资产-旧', res?.keYongMoney, res);
    setKeYongMoney(res?.keYongMoney > 0 ? res?.keYongMoney : 0);
  }

  // 获取可用资产-新
  async function getKeYongMoneyNew() {
    const res: any = (await keYongMoneyApi({ isNew: true }))?.data;
    setKeYongMoneyNew(res?.keYongMoney > 0 ? res?.keYongMoney : 0);
    // =====
    // positions
    const positionData = res.positions[0];
    const baoZhengJin = positionData?.baoZhengJin;
    const weiShiXianYingKui = positionData?.weiShiXianYingKui?.num;
    const yiShiXianYingKui = positionData?.ysxYingKui?.pnl;
    console.log('下单页', -baoZhengJin, weiShiXianYingKui, yiShiXianYingKui);
    const { allMoney, position, keYong } = res?.tongJiRes;
    console.log('计算', allMoney, position, keYong);
    // console.log('res: 获取可用资产-新', res?.keYongMoney, res);
    console.log('==============================');
  }

  // 设置杠杆成功后刷新
  function reload() {
    getContractAccount();
    getKeYongMoney();
    getKeYongMoneyNew();
  }

  return (
    <>
      <div className={`${styles.submitOrderw} pageRightWidth zcard`}>
        <div className={`${styles.header} center-v`}>交易 </div>
        <div className={`${styles.pagecon} xxx`}>
          <div className={`${styles.leverwrap} `} onClick={() => setOpenLever(true)}>
            <div className={`${styles.ltype} `}>{positionType === 'zhu' ? '逐仓' : '全仓'} </div>
            <div className={`${styles.num} `}>{lever}x</div>
            <div className={`${styles.licon} `}>
              <CaretDownOutlined />
            </div>
          </div>
          <div className={`${styles.tabw} xxx`}>
            {tablist.map((item: any, i: number) => (
              <div
                className={`${styles.item} ${curTab === item.key && styles.itemAct} `}
                key={i}
                onClick={() => setCurTab(item.key)}
              >
                {item.title}
              </div>
            ))}
          </div>
          <div className={`${styles.orderinfo}`}>
            {curTab === 'xianJia' && (
              <div className={`${styles.item} ${styles.priceItem}`}>
                <InputNumber
                  prefix="价格"
                  value={price}
                  size="large"
                  onChange={(value) => setPrice(value)}
                />
                <div className={`${styles.oicon}`}>
                  <div className={`${styles.icons} xxx`}>
                    <div className={`${styles.icon} xxx`} onClick={() => changePrice(0.1)}>
                      <UpOutlined />
                    </div>
                    <div className={`${styles.icon} xxx`} onClick={() => changePrice(-0.1)}>
                      <DownOutlined />
                    </div>
                  </div>
                </div>
              </div>
            )}
            <Tooltip
              title={
                <span style={{ fontSize: '12px' }}>
                  {`最小下单数量: ${minNum} USDT ≈ ${coinData?.quanto_multiplier} ${coinData?.name?.split('_')[0]}`}
                </span>
              }
            >
              <div className={`${styles.item} ${styles.numItem}`}>
                <InputNumber
                  prefix="数量"
                  value={num}
                  size="large"
                  onChange={(value) => setNum(value)}
                />
                <div className={`${styles.oicon}`}>
                  <div className={`${styles.danwei} xxx`}>{unit?.name}</div>
                  {/* === 选择数量单位-勿删 */}
                  {/* <div className={`${styles.icons} center`} onClick={() => setOpen(true)}>
                  <div className={`${styles.icon} xxx`}>
                    <DownOutlined />
                  </div>
                </div> */}
                </div>
              </div>
            </Tooltip>
            <div className={`${styles.canusew} flex`}>
              {/* ppp 可用余额 */}
              <div className={`${styles.txt} xxx`}>可用</div>
              <div className={`${styles.num} xxx`}>
                {Number(keYongMoneyNew).toFixed(2)} USDT
                {isLocal() && (
                  <>
                    {/* <div>{Number(keYongMoney).toFixed(2)} USDT (旧)</div> */}
                    <div>{keYongMoneyNew}</div>
                  </>
                )}
              </div>
            </div>
            <TradeStrategy ref={zhiYingRef} curTab={curTab} />
            <div className={`${styles.mmbtnsw} flex`}>
              {isLocal() ? (
                <>
                  <Button loading={buyLoading} onClick={() => buy(false)}>
                    买入做多
                  </Button>
                  <Button loading={sellLoading} onClick={() => buy(true)}>
                    卖出做空
                  </Button>
                </>
              ) : (
                <>
                  <MyButton text="买入做多" loading={buyLoading} onClick={() => buy(false)} />
                  <MyButton
                    text="卖出做空"
                    loading={sellLoading}
                    styles={{ backgroundColor: '#1bb273' }}
                    onClick={() => buy(true)}
                  />
                </>
              )}
            </div>
            {isLocal() && (
              <BaoZhengJin
                keYongMoney={keYongMoney}
                account={account}
                price={price}
                coinData={coinData}
                lever={lever}
                num={num}
                unit={unit?.value}
              />
            )}
          </div>
        </div>
        <div className={`${styles.xxx} xxx`}></div>
      </div>

      {/* 杠杆弹框 */}
      {openLever && (
        <LeverModal
          contract={coinData}
          open={openLever}
          setOpen={setOpenLever}
          positionType={positionType}
          setPositionType={setPositionType}
          lever={lever}
          setLever={setLever}
          getContractAccount={getContractAccount}
          reload={reload}
        />
      )}
      {/* 单位弹框 */}
      <UnitModal open={open} setOpen={setOpen} units={units} unit={unit} setUnit={setUnit} />
    </>
  );
}
